package com.globefrog.framework.log.handler;

import com.globefrog.framework.common.enums.ActionResultEnum;
import com.globefrog.framework.log.ActionLog;
import com.globefrog.framework.log.ActionLogImpl;
import jdk.nashorn.internal.ir.annotations.Ignore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.TypeMismatchException;
import org.springframework.stereotype.Component;

/**
 * @Author: caijinbang
 * @Description:
 * @Date: Create in 2021-01-10
 */
@Slf4j
@Component
public class ErrorHandler {

  private final ActionLogImpl actionLogger = ActionLogImpl.getInstance();


  public void handle(Throwable throwable) {
    if (!this.isIgnore(throwable)) {
      if (this.isWarning(throwable)) {
        this.logWarning(throwable);
      } else {
        this.logError(throwable);
      }
    }
  }

  private boolean isIgnore(Throwable e) {
    return null == e || e.getClass().isAnnotationPresent(Ignore.class);
  }

  private boolean isWarning(Throwable e) {
    return this.isWarningException(e);
  }

  private boolean isWarningException(Throwable e) {
    return e instanceof TypeMismatchException || e instanceof IllegalArgumentException;
  }

  private void logError(Throwable e) {
    ActionLog actionLog = this.actionLogger.currentActionLog();
    if (actionLog != null) {
      actionLog.setResult(ActionResultEnum.ERROR);
      actionLog.setException(e.getClass().getName());
      actionLog.setErrorMessage(e.getMessage());
    }
    log.error(e.getMessage(), e);
  }

  private void logWarning(Throwable e) {
    ActionLog actionLog = this.actionLogger.currentActionLog();
    if (actionLog != null) {
      actionLog.setResult(ActionResultEnum.WARNING);
      actionLog.setException(e.getClass().getName());
      actionLog.setErrorMessage(e.getMessage());
    }
    log.info(e.getMessage(), e);
  }
}
